package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import jdk.vm.ci.meta.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api(tags = "C端-菜品相关接口")
@Slf4j
@RequestMapping("/user/dish")
@RestController("userDishController")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @ApiOperation("根据分类id查询菜品")
    @GetMapping("/list")
    public Result<List<DishVO>> list(Long categoryId){
        //缓存优化
        //查询MySql数据，先判断redis缓存中是否存在数据
        String key = "dish_" + categoryId;
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        //如果有缓存数据，直接返回
        if (dishVOList != null && dishVOList.size() > 0){
            return Result.success(dishVOList);
        }

        //如果没有数据，查询MySQL数据库
        log.info("根据分类id查询菜品：{}", categoryId);
        //构造菜品对象，并设置categoryId和状态为起售中
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);

        List<DishVO> list = dishService.listWithCDishVO(dish);

        //将MySQL查询到的数据存入redis缓存中
        redisTemplate.opsForValue().set(key, list);

        return Result.success(list);
    }
}
